//
//  main.c
//  Symbol Table
//
//  Created by Pei Liu on 10/4/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#include"hashtable.h"
#include<stdio.h>
#include "string.h"
#define DEFAULT 32

char* str(int i, int j, char* s);

int main(int argc, const char * argv[])
{
    HASHTBL* symboltbl;
    
    if(!(symboltbl = hashtbl_create(DEFAULT, NULL))) 
    {
		printf("ERROR: Create Symbol Table Failed\n");
		exit(0);
	}

    printf("USAGE: insert, lookup, quit.\n> ");
    
    char *op = malloc(sizeof(8)); 
    char *name = malloc(sizeof(20));
    char *type = malloc(sizeof(20));
    size_t size;
    
    getline(&op, &size, stdin);
    
    op = str(0,(int)(strlen(op) - 2), op);
    while(strcmp(op, "quit"))
    {
        //insert
        if (!strcmp(op, "insert")) 
        {
            printf("> NAME: ");
            
            getline(&name, &size, stdin);
            name = str(0,(int)(strlen(name) - 2), name);
            
            printf("> TYPE: ");
            
            getline(&type, &size, stdin);
            type = str(0,(int)(strlen(type) - 2), type);
            
            if(hashtbl_insert(symboltbl, name, type, 0, 0) == -1)
            {
                printf("NAME CONFLICT!\n");
            }
            else
            {
                printf("Insert Successfully!\n");
            }
        }
        //lookup
        else if(!strcmp(op, "lookup"))
        {
            printf("> NAME: ");
            
            getline(&name, &size, stdin);
            name = str(0,(int)(strlen(name) - 2), name);
            if(!hashtbl_get(symboltbl, name))
            {
                printf("NO SUCH IDENTIFIER!\n");
            }
            else
                PrintEntry(hashtbl_get(symboltbl, name));
        }
        
        //get operation again
        printf("> ");
        getline(&op, &size, stdin);
        op = str(0,(int)(strlen(op) - 2), op);

    }
   	    
    
    hashtbl_trav(symboltbl);
	hashtbl_destroy(symboltbl);
    
	return 0;
}

//format the string input
char* str(int i, int j, char* s)
{
    char* temp = malloc(sizeof(20));
    int k = 0;
    
    for(k = i; k <= j; k++)
    {
        temp[k-i] = s[k];
    }
    temp[j-i+1] = 0;
    
    return temp;
}

